package com.ikan.positionserver.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.ikan.positionserver.dto.*;
import com.ikan.positionserver.entity.Device;
import com.ikan.positionserver.entity.Rack;
import com.ikan.positionserver.entity.TenantHost;
import com.ikan.positionserver.enums.DeviceTypeEnum;
import com.ikan.positionserver.response.JsonReturn;
import com.ikan.positionserver.service.IDeviceService;
import com.ikan.positionserver.service.IRackService;
import com.ikan.positionserver.service.ITenantHostService;
import com.ikan.positionserver.util.DeviceConverter;
import com.ikan.positionserver.util.StringFormatUtil;
import com.ikan.positionserver.util.TenantHostConverter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * device前端控制器  RestController注解 将结果以JSON形式返回
 * </p>
 *
 * @author ikan
 * @since 2024-04-15
 */
@Slf4j
@RestController
@RequestMapping("/device")
@Api(value = "Device", tags = "Device")
public class DeviceController {
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IRackService rackService;

    @Autowired
    private ITenantHostService tenantHostService;

    /**
     * POST请求方式
     *
     * @param device 保存的对象
     * @return JsonReturn
     */
    @PostMapping("saveOrUpdate")
    @ApiOperation(value = "插入记录")
    public JsonReturn saveOrUpdate(@RequestBody Device device) {
        try {
            log.info("保存设备, device:{}", device);
            QueryWrapper<Device> rackQueryWrapper = new QueryWrapper<>();
            rackQueryWrapper.eq("rack_name", device.getRackName());
            rackQueryWrapper.eq("u_start_id", device.getUStartId());
            Device queryDevice = deviceService.getOne(rackQueryWrapper);
            boolean result = false;
            if (queryDevice == null) {
                log.info("新增设备, device:{}", device);
                device.setCreateTime(new Date());
                device.setCreator("system");
                deviceService.save(device);
                result = true;
            } else {
                log.info("更新设备, device:{}", device);
                device.setId(queryDevice.getId());
                deviceService.updateById(device);
                result = true;
            }
            return JsonReturn.buildSuccess(result ? "保存设备成功" :
                    "保存设备失败");
        } catch (Exception e) {
            log.error("新增失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        }

    }

    /**
     * PUT请求方式
     *
     * @param device 要修改的对象
     * @return JsonReturn
     */
    @PutMapping
    @ApiOperation(value = "修改记录")
    public JsonReturn update(Device device) {
        try {
            return JsonReturn.buildSuccess(deviceService.updateById(device) ? device :
                    "device--修改失败");
        } catch (Exception e) {
            log.error("修改失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        }

    }

    /**
     * 批量删除 DELETE请求方式
     *
     * @param ids Long 类型 List 集合
     * @return JsonReturn
     */
    @DeleteMapping("remove")
    @ApiOperation(value = "删除多条记录")
    public JsonReturn delete(@RequestBody List<Long> ids) {
        try {
            deviceService.removeByIds(ids);
            return JsonReturn.buildSuccess(ids, "操作成功");
        } catch (Exception e) {
            log.error("操作失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        }
    }

    /**
     * 查询一个 GET请求
     *
     * @param id 查找对象的主键ID
     * @return JsonReturn
     */
    @GetMapping("findOne/{id}")
    @ApiOperation(value = "查询单条记录")
    public JsonReturn findOne(@PathVariable("id") Long id) {
        try {
            Device device = deviceService.getById(id);
            return JsonReturn.buildSuccess(device, "操作成功");
        } catch (Exception e) {
            log.error("查询单个失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        }
    }

    /**
     * 查询所有 GET
     *
     * @param pageNum  当前页
     * @param pageSize 每页最大数据数
     * @return JsonReturn
     */
    @GetMapping("findAll/{pageNum}/{pageSize}")
    @ApiOperation(value = "分页查询")
    public JsonReturn findAll(@PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
        try {
            Page<Device> page = deviceService.page(new Page<Device>(pageNum, pageSize));
            return JsonReturn.buildSuccess(page, "操作成功");
        } catch (Exception e) {
            log.error("分页查询失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        }
    }


    /**
     * 解析服务器信息
     *
     * @return JsonReturn
     */
    @GetMapping("parseDeviceList")
    @ApiOperation(value = "解析设备信息")
    public JsonReturn parseDeviceList(DeivceInitRequestDto requestDto) {
        List<String> resultList = Lists.newArrayList();
        try {
            QueryWrapper<Rack> rackQueryWrapper = new QueryWrapper<>();
            rackQueryWrapper.eq("name", requestDto.getRackName());
            List<Rack> rackList = rackService.list(rackQueryWrapper);
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByCode(requestDto.getDeviceType());

            int startUnit = 0;

            if (CollectionUtils.isNotEmpty(rackList)) {
                Rack rack = rackList.get(0);
                String[] serverArr = StringUtils.split(requestDto.getServerList(), " ");
                List<String> serverList = Lists.newArrayList();
                for (int i = 0; i < serverArr.length; i++) {
                    serverList.add(serverArr[i]);
                }

                Collections.reverse(serverList);
                for (int i = 0; i < serverList.size(); i++) {
                    if (StringUtils.isEmpty(requestDto.getStartUnit())) {
                        startUnit = 3 + 2 * (i + 1);
                    } else {
                        startUnit = Integer.valueOf(requestDto.getStartUnit());
                    }

                    String result = StringFormatUtil.format(
                            "insert into `server` (name,rack_id,rack_name,u_start_id,device_type,height,create_time,creator)" +
                                    "values('{}',{},'{}',{},'{}',{},{},'{}');",
                            serverList.get(i),
                            rack.getId(),
                            rack.getName(),
                            startUnit,
                            deviceTypeEnum.getType(),
                            deviceTypeEnum.getHeight(),
                            "now()",
                            "system"
                    );
                    resultList.add(result);
                }
            }

            return JsonReturn.buildSuccess(resultList, "操作成功");
        } catch (Exception e) {
            log.error("操作失败", e);
            return JsonReturn.buildFailure("操作失败" + e.getMessage());
        }
    }


    @PostMapping("queryHost")
    @ApiOperation(value = "查询主机")
    public JsonReturn queryHost(@RequestBody HostQueryRequestDto hostQueryRequestDto) {
        try {
            HostQueryResultDO hostQueryResultDO = new HostQueryResultDO();
            QueryWrapper<Device> deviceQueryWrapper = new QueryWrapper<>();
            deviceQueryWrapper.eq("biz_ip", hostQueryRequestDto.getHostIp());
            List<Device> deviceList = deviceService.list(deviceQueryWrapper);
            if (CollectionUtils.isNotEmpty(deviceList)) {
                Device device = deviceList.get(0);
                DeviceDto deviceDto = DeviceConverter.convert2Dto(device);
                hostQueryResultDO.setDeviceDto(deviceDto);

                QueryWrapper<TenantHost> tenantHostQueryWrapper = new QueryWrapper<>();
                tenantHostQueryWrapper.eq("host_ip", device.getBizIp());
                List<TenantHost> tenantHostList = tenantHostService.list(tenantHostQueryWrapper);
                List<TenantHostDto> tenantHostDtoList = TenantHostConverter.convertList2Dto(tenantHostList);
                hostQueryResultDO.setTenantHostDtoList(tenantHostDtoList);
            }
            return JsonReturn.buildSuccess(hostQueryResultDO, "操作成功");
        } catch (Exception e) {
            log.error("查询主机失败", e);
            return JsonReturn.buildFailure("查询主机操作失败" + e.getMessage());
        }
    }
}
